﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using Styx.Common;

namespace BattleBuddyplug
{
    internal static class Updater
    {
        private const string PbSvnUrl = "http://battlebuddy.googlecode.com/svn/trunk/ battlebuddy/"; // Code svn

        private static readonly Regex _linkPattern = new Regex(@"<li><a href="".+"">(?<ln>.+(?:..))</a></li>",
                                                               RegexOptions.CultureInvariant);


        public static void CheckForUpdate(string path, bool checkallow=true)
        {
            try
            {
                string remoteRev = GetRevision();
                BBLog.LogAlways(
                    "Using BattleBuddy version: " +
                    BattleBuddy._MySettings.CurrentRevision +
                    ". Current version is: " +
                    remoteRev);
                if (BattleBuddy._MySettings.CurrentRevision != remoteRev)
                {
                    string logwrt = "";
                    if (BattleBuddy._MySettings.AllowAutoUpdate) { logwrt = "Downloading Update"; } else { logwrt = "Please update!"; };
                    BBLog.LogAlways("A new version was found. " + logwrt);
                    if (!BattleBuddy._MySettings.AllowAutoUpdate && checkallow) return;

                    DownloadFilesFromSvn(new WebClient(), PbSvnUrl, path);
                    BBLog.Log("Download complete.");
                    BattleBuddy._MySettings.CurrentRevision = remoteRev;
                    BattleBuddy._MySettings.Save();

                    BBLog.LogAlways("A new version of BattleBuddy was installed. Please restart Honorbuddy");
                }
                else
                {
                    BBLog.Log("No updates found");
                }
            }
            catch (Exception exc)
            {
                BBLog.LogException(exc);
            }
        }

        private static string GetRevision()
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            string versionpath = PbSvnUrl + "version";
            BBLog.Log("Getting version from: " + versionpath);
            string webData = wc.DownloadString(versionpath);
            return webData;
        }


        private static void DownloadFilesFromSvn(WebClient client, string url, string path)
        {
            string html = client.DownloadString(url);
            MatchCollection results = _linkPattern.Matches(html);

            IEnumerable<Match> matches = from match in results.OfType<Match>()
                                         where match.Success && match.Groups["ln"].Success
                                         select match;
            foreach (Match match in matches)
            {
                string file = RemoveXmlEscapes(match.Groups["ln"].Value);
                string newUrl = url + file;
                //Logging.Write(url);
                if (newUrl[newUrl.Length - 1] == '/') // it's a directory...
                {
                    if (!newUrl.Contains("PetSettings") && !newUrl.Contains("CalcEngine")) DownloadFilesFromSvn(client, newUrl, path);
                }
                else // its a file.
                {
                    string filePath, dirPath;
                    if (url.Length > PbSvnUrl.Length)
                    {
                        string relativePath = url.Substring(PbSvnUrl.Length);
                        dirPath = Path.Combine(path, relativePath);
                        filePath = Path.Combine(dirPath, file);
                    }
                    else
                    {
                        dirPath = Environment.CurrentDirectory;
                        filePath = Path.Combine(path, file);
                    }
                    Logging.Write("Downloading {0}", file);
                    try
                    {
                        if (!Directory.Exists(dirPath))
                            Directory.CreateDirectory(dirPath);
                        client.DownloadFile(newUrl, filePath);
                        //Logging.Write("Download {0} done", file);
                    }
                    catch (Exception exc)
                    {
                        BBLog.LogException(exc);
                    }

                }
            }
        }

        private static string RemoveXmlEscapes(string xml)
        {
            return
                xml.Replace("&amp;", "&").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&quot;", "\"").Replace(
                    "&apos;", "'");
        }
    }
}